<?php

use PaypalPayoutsSDK\Core\PayPalHttpClient;
use PaypalPayoutsSDK\Core\ProductionEnvironment;
use PaypalPayoutsSDK\Core\SandboxEnvironment;
use PaypalPayoutsSDK\Payouts\PayoutsPostRequest;

require __DIR__  . '/vendor/autoload.php';

error_reporting(E_ALL);

// 回调类型
function sendBack($data, $msg='', $code=200){
    $backinfo = json_encode([
        'code'=> $code,
        'msg' => $msg,
        'data'=> $data,
    ]);
    echo $backinfo;
    exit();
}

// Creating an environment
$clientId = "AVQ68-wx9VQrSNHfJTg2PWTWr37_6-nE-XRQV6pf2wro3ZUG70Wt29qaeQHKhGldyE55AsGgRZykzNQN";
$clientSecret = "EPnwkDY6xOUDCRJP0dBA9KeB8ckxAndYmE7djY7ZpUbistKPaCFQZV7HLDGqlIK7WZF1SK0CcXYYdc2l";
define('SANDBOX', true);


if(SANDBOX){
    $environment = new SandboxEnvironment($clientId, $clientSecret);
} else {
    $environment = new ProductionEnvironment($clientId, $clientSecret);
}


// $body = [
//     'sender_batch_header'=>[
//         'sender_batch_id' => 'Payouts_2021_06251413',
//         'email_subject'   => 'You have a payout!',
//         'email_message'   => 'You have received a payout! Thanks for using our service!',
//     ],
//     'items' => [
//         [
//             'recipient_type'=> 'EMAIL',     // EMAIL PHONE PAYPAL_ID
//             'amount'        => [
//                 'value' => '9.87',
//                 'currency' => 'USD',
//             ],
//             'note' => 'Thanks for your patronage!', //发件人为通知指的便笺
//             'receiver' => 'sb-m7rgv6592237@business.example.com',       //收款人
//             'sender_item_id' => '20210625',     // item 的编号
            


//             // "note": "Thanks for your patronage!",
//             // "sender_item_id": "201403140001",
//             // "receiver": "receiver@example.com",
//             // "alternate_notification_method": {
//             //     "phone": {
//             //     "country_code": "91",
//             //     "national_number": "9999988888"
//             //     }
//             // },
//             // "notification_language": "fr-FR"
//         ]
//     ]
// ];

$jsonBody = file_get_contents("php://input");
$body = json_decode($jsonBody, true);


try {
    $client = new PayPalHttpClient($environment);
    $request = new PayoutsPostRequest();
    $request->body = $body;
    $response = $client->execute($request);
} catch (Exception $e) {
    sendBack(['error'=>$e->getMessage()], '出现异常啦~', 400);
}
if(isset($response->result->batch_header->errors)) {
    sendBack(['error'=>$response->result->batch_header->errors], '出错啦~', 404);
}
sendBack($response->result, 'payout success~', 200);
